import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // 检查是否有用户基本信息
      const hasUserInfo = store.getters.name && store.getters.name !== ''

      if (hasUserInfo) {
        next()
      } else {
        try {
          // 尝试获取用户信息（简化版）
          await store.dispatch('user/getInfo')
          next()
        } catch (error) {
          console.error('获取用户信息失败:', error)
          await store.dispatch('user/resetToken')
          showSafeMessage('登录状态已过期，请重新登录')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

// 安全的消息显示函数
function showSafeMessage(error) {
  const errorMessage = getErrorMessage(error)

  try {
    if (Message && typeof Message.error === 'function') {
      Message.error(errorMessage)
    } else {
      fallbackMessage(errorMessage)
    }
  } catch (e) {
    console.error('Message component error:', e)
    fallbackMessage(errorMessage)
  }
}

// 获取错误信息
function getErrorMessage(error) {
  if (typeof error === 'string') {
    return error
  } else if (error && error.message) {
    return error.message
  } else {
    return '系统错误'
  }
}

// 回退的消息显示方法
function fallbackMessage(message) {
  console.error('Error:', message)
}
